package br.com.automed.bean;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import br.com.automed.entity.Consulta;
import br.com.automed.entity.MatriculaValida;
import br.com.automed.entity.Paciente;
import br.com.automed.form.MarcacaoConsultaPacienteForm;
import br.com.automed.jpautil.JPAUtil;
import br.com.automed.service.ConsultaBusiness;
import br.com.automed.service.UsuarioBusiness;
import br.com.automed.util.Util;

@Named(value="marcacaoConsultaPacienteBean")
@SessionScoped
public class MarcacaoConsultaPacienteBean implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3742936677968313354L;
	private MarcacaoConsultaPacienteForm form;
	@Inject
	private UsuarioLogadoBean usuarioBean;
	
	public MarcacaoConsultaPacienteBean() {
		form = new MarcacaoConsultaPacienteForm();
	}
			
	@SuppressWarnings("unchecked")
	public void buscarConsultas(){
		
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("param", form.getAreaMedica());
		form.setConsultas((List<Consulta>)JPAUtil.list("Consulta.buscaConsultaPorArea", param));
	}
	
	public void listarConsultasMarcadas(){
		
		if((form.getDataInicio() != null) && (form.getDataFim() != null)){
			
			if(form.getDataInicio().after(form.getDataFim())){
				
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary("Data inicial maior que a final");
				FacesContext.getCurrentInstance().addMessage(null, message);
				return;
			}
		}
		
		StringBuilder sql = new StringBuilder();
		HashMap<String, Object> params = new HashMap<String, Object>();
		sql.append("select o from Consulta o where o.paciente = :paciente");
		params.put("paciente", (Paciente)JPAUtil.get(Paciente.class, usuarioBean.getForm().getUsuario().getIdUsuario()));
		
		
		if((form.getDataInicio() != null) && (form.getDataFim() != null)){
			
			sql.append(" and o.dataConsulta >= :fistDate and o.dataConsulta <= :lastDate");
			Calendar firstDate = Calendar.getInstance(Locale.getDefault());
			Calendar lastDate =  Calendar.getInstance(Locale.getDefault());
			firstDate.setTime(form.getDataInicio());
			lastDate.setTime(form.getDataFim());
			
			firstDate.set(Calendar.HOUR, 0);
			firstDate.set(Calendar.MINUTE, 0);
			firstDate.set(Calendar.SECOND, 0);
			
			lastDate.set(Calendar.HOUR, 23);
			lastDate.set(Calendar.HOUR, 59);
			lastDate.set(Calendar.SECOND, 59);
			
			params.put("fistDate", firstDate.getTime());
			params.put("lastDate", lastDate.getTime());
			
		}else if(form.getDataInicio() != null){
			sql.append(" and o.dataConsulta >= :fistDate");
			params.put("fistDate", form.getDataInicio());
			
		}else if(form.getDataFim() != null){
			sql.append(" and o.dataConsulta <= :lastDate");
			params.put("lastDate", form.getDataFim());
		}
		
		sql.append(" order by o.dataConsulta asc");
		
		List<Consulta> list  = (List<Consulta>) JPAUtil.createQuery(sql.toString(), params);
		
		form.setConsultasDoPaciente(list);

	}
	
	public List<Consulta> getConsultasMarcadas(){
		
		StringBuilder sql = new StringBuilder();
		HashMap<String, Object> params = new HashMap<String, Object>();
		sql.append("select o from Consulta o where o.paciente = :paciente");
		params.put("paciente", (Paciente)JPAUtil.get(Paciente.class, usuarioBean.getForm().getUsuario().getIdUsuario()));
		sql.append(" and o.flagAtendido = 'N'");
		sql.append(" order by o.dataConsulta");
		
		List<Consulta> list  = (List<Consulta>) JPAUtil.createQuery(sql.toString(), params);

		
		return list;
	}
	
	public void marcarConsulta(){
		form.setCadastrado(false);
		if(ConsultaBusiness.getInstancia().marcarConsulta(form.getConsultaSelecionada(), (Paciente) JPAUtil.get(Paciente.class, usuarioBean.getForm().getUsuario().getIdUsuario()))){
			form.setCadastrado(true);
		}
	}
	
	public void cancelarMarcacaoConsulta(){
		
		if(ConsultaBusiness.getInstancia().cancelarConsulta(form.getConsultaModal())){
			form.setConsultaCancelada(true);
		}else{
			form.setConsultaCancelada(false);
		}
		
	}
	
	public String getStatusConsulta(Consulta consulta){
		
		String status = null;
		
		if(consulta.getPaciente() != null){
			if(consulta.getPaciente().getIdUsuario().equals(usuarioBean.getForm().getUsuario().getIdUsuario())){
				status = "USER_CURRENT";
			}else{
				status = "INDISP";
			}
		}else{
			status = "DISP";
		}
		
		return status;
	}
	
	public boolean verificaCancelaConsulta(Date dataConsulta){
		
		boolean faltamMenosDe24Horas = false;
		
		Calendar toDay = Calendar.getInstance(Locale.getDefault());
		Calendar dtConsulta = Calendar.getInstance(Locale.getDefault());
		dtConsulta.setTime(dataConsulta);
		
		long horas = ((((dtConsulta.getTimeInMillis()) - toDay.getTimeInMillis()) / 1000) / 60) / 60;
		
		if(horas <= 24){
			form.setQtdHoras((int)horas);
			faltamMenosDe24Horas = true;
		}
		return faltamMenosDe24Horas;
	}
	
	public String carregaPaciente(){
//		if(form.getPaciente() == null){
			form.setPaciente((Paciente)JPAUtil.get(Paciente.class, usuarioBean.getForm().getUsuario().getIdUsuario()));
//		}
				
		return "editar_paciente";
	}
	
	public void atualizarDadosPaciente(){
		
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		
		MatriculaValida mv = UsuarioBusiness.verificaMatriculaPaciente(form.getPaciente().getMatricula());
		
		
		if(mv == null || mv.getFlagAtivo().equals("B") || !mv.getConvenio().getIdConvenio().equals(form.getPaciente().getConvenio().getIdConvenio())){
			
			FacesMessage message = new FacesMessage();
			message.setSummary(Util.getMessage("display.validator.matricula", null));
			message.setSeverity(FacesMessage.SEVERITY_INFO);
			
			FacesContext.getCurrentInstance().addMessage("matricula", message);
			return;
		}
		
		if(form.getPaciente() != null && JPAUtil.update(form.getPaciente())){
			request.setAttribute("status", "sucess");
			
		}else{
			request.setAttribute("status", "error");
		}
	}
	
	public void alterarSenha(){
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		if(form.getPaciente().getSenha().equals(form.getSenhaAntiga()) && form.getNovaSenha().equals(form.getRepetirNovaSenha())){
			
			form.getPaciente().setSenha(form.getNovaSenha());
			JPAUtil.update(form.getPaciente());			
			request.setAttribute("password_sucess", "sucesso");
		}else{
			request.setAttribute("password_sucess", "erro");			
		}
		form.setSenhaAntiga(null);
		form.setNovaSenha(null);
		form.setRepetirNovaSenha(null);
		
	}
	
	public void carregarConsulta(Consulta c){
		form.setConsultaModal(c);
	}
	
	public void addConsultaSelecionada(Consulta consulta){
		form.setConsultaSelecionada(consulta);
	}

	public MarcacaoConsultaPacienteForm getForm() {
		return form;
	}

	public void setForm(MarcacaoConsultaPacienteForm form) {
		this.form = form;
	}
	
}